<script lang="ts" setup>
import type { VbenFormProps } from '#/adapter/form';
import type { VxeGridProps } from '#/adapter/vxe-table';

import { ref, reactive } from 'vue';

import { Page, useVbenDrawer } from '@vben/common-ui';

import { Button, Tag, message } from 'ant-design-vue';
import dayjs from 'dayjs';

import { useVbenVxeGrid } from '#/adapter/vxe-table';
import { queryJobList, updateJobStatus, queryJobCount } from '#/api';

import ExtraDrawer from './Drawer.vue';

const tTime = (time) => dayjs(time).format('YYYY-MM-DD HH:mm:ss');

const jobCount = reactive({
  total_tasks: 0,
  inactive_tasks: 0,
  active_tasks: 0,
  total_calls: 0,
  success_calls: 0,
  failed_calls: 0,
});

function reloadJobCount() {
  queryJobCount().then((r) => {
    Object.assign(jobCount, r);
  });
}
interface RowType {
  category: string;
  color: string;
  id: string;
  price: string;
  productName: string;
  releaseDate: string;
}

const formOptions: VbenFormProps = {
  // 默认展开
  schema: [
    {
      component: 'Input',
      fieldName: 'searchContent',
      componentProps: {
        placeholder: '请输入任务名称模糊查询',
      },
      label: '任务名称',
    },
  ],
  // 控制表单是否显示折叠按钮
  showCollapseButton: false,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
};
const pageTotal = ref(0);
const gridOptions: VxeGridProps<RowType> = {
  checkboxConfig: {
    highlight: true,
    labelField: 'name',
  },
  columns: [
    {
      title: '任务名称',
      field: 'name',
    },
    {
      title: '任务描述',
      field: 'description',
    },
    {
      title: '推送内容',
      field: 'push_content',
    },
    {
      title: 'CRON表达式',
      field: 'cron_expression',
    },
    {
      title: '状态',
      field: 'status',
      slots: { default: 'status' },
    },
    {
      title: '是否推送',
      field: 'push_status',
      slots: { default: 'push' },
    },
    {
      title: '创建时间',
      field: 'created_at',
      slots: { default: 'created' },
    },
    {
      title: '更新时间',
      field: 'updated_at',
      slots: { default: 'updated' },
    },
    {
      field: 'action',
      fixed: 'right',
      slots: { default: 'action' },
      title: '操作',
      width: 140,
    },
  ],
  pagerConfig: {
    pageSize: 10,
  },
  keepSource: true,
  proxyConfig: {
    ajax: {
      query: async ({ page }, formValues) => {
        const data = await queryJobList({
          page: page.currentPage,
          pageSize: page.pageSize,
          ...formValues,
        });
        pageTotal.value = data.total;
        reloadJobCount();
        return data;
      },
    },
  },
  toolbarConfig: {
    // 是否显示搜索表单控制按钮
    // @ts-ignore 正式环境时有完整的类型声明
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
};

const [Grid, gridApi] = useVbenVxeGrid({ formOptions, gridOptions });
function updateRow(id, status) {
  updateJobStatus({ id, status }).then(() => {
    gridApi.reload();
    reloadJobCount();
    if (status) {
      message.success('启动成功');
    } else {
      message.success('暂停成功');
    }
  });
}

const [Drawer, drawerApi] = useVbenDrawer({
  // 连接抽离的组件
  connectedComponent: ExtraDrawer,
  onOpenChange(isOpen) {
    if (!isOpen) {
      gridApi.reload();
      reloadJobCount();
    }
  },
});
</script>

<template>
  <div>
    <div class="stats-container bg-background text-foreground">
      <div class="stats-grid">
        <!-- 全部任务 -->
        <div class="stat-item">
          <div class="stat-label">全部任务</div>
          <div class="stat-value">{{ jobCount.total_tasks }}</div>
        </div>

        <!-- 暂停任务 -->
        <div class="stat-item">
          <div class="stat-label">暂停任务</div>
          <div class="stat-value">{{ jobCount.inactive_tasks }}</div>
        </div>

        <!-- 调度次数 -->
        <div class="stat-item">
          <div class="stat-label">调度次数</div>
          <div class="stat-value">{{ jobCount.total_calls }}</div>
        </div>

        <!-- 进行中 -->
        <div class="stat-item status-running">
          <div class="stat-label">
            <span class="status-indicator"></span>
            进行中
          </div>
          <div class="stat-value">{{ jobCount.active_tasks }}</div>
        </div>

        <!-- 调度成功 -->
        <div class="stat-item status-success">
          <div class="stat-label">
            <span class="status-indicator"></span>
            调度成功
          </div>
          <div class="stat-value">{{ jobCount.success_calls }}</div>
        </div>

        <!-- 调度失败 -->
        <div class="stat-item status-failure">
          <div class="stat-label">
            <span class="status-indicator"></span>
            调度失败
          </div>
          <div class="stat-value">{{ jobCount.failed_calls }}</div>
        </div>
      </div>
    </div>
    <Page>
      <div class="vp-raw w-full">
        <Grid>
          <template #toolbar-tools>
            <Button
              class="mr-2"
              type="primary"
              @click="drawerApi.setData({ push_status: 1 }).open()"
            >
              新增
            </Button>
          </template>
          <template #action="{ row }">
            <Button
              danger
              type="link"
              @click="updateRow(row.id, 0)"
              v-if="row.status === 1"
            >
              暂停
            </Button>
            <Button
              type="link"
              @click="updateRow(row.id, 1)"
              v-if="row.status === 0"
            >
              启动
            </Button>
            <Button type="link" @click="drawerApi.setData(row).open()">
              编辑
            </Button>
          </template>
          <template #status="{ row }">
            <Tag color="green" v-if="row.status === 1">启用</Tag>
            <Tag color="red" v-else>暂停</Tag>
          </template>
          <template #created="{ row }">
            {{ tTime(row.created_at) }}
          </template>
          <template #updated="{ row }">
            {{ tTime(row.updated_at) }}
          </template>
          <template #push="{ row }">
            {{ row.push_status === 1 ? '是' : '否' }}
          </template>
        </Grid>
      </div>
      <Drawer />
    </Page>
  </div>
</template>

<style scoped>
.stats-container {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  margin: 20px 20px 0 20px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 20px;
  justify-content: center;
}

.stat-item {
  text-align: center;
  padding: 16px;
  border-radius: 6px;
  transition: transform 0.2s ease;
}

.stat-item:hover {
  transform: translateY(-2px);
}

.stat-label {
  font-size: 14px;
  color: #666;
  margin-bottom: 12px;
  font-weight: 500;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  margin-bottom: 8px;
}

.status-indicator {
  display: inline-block;
  width: 8px;
  height: 8px;
  border-radius: 50%;
  margin-right: 6px;
}

.status-running .status-indicator {
  background-color: #1890ff; /* 蓝色 - 进行中 */
}

.status-success .status-indicator {
  background-color: #52c41a; /* 绿色 - 成功 */
}

.status-failure .status-indicator {
  background-color: #ff4d4f; /* 红色 - 失败 */
}

/* 响应式设计 */
@media (max-width: 768px) {
  .stats-grid {
    grid-template-columns: repeat(auto-fit, minmax(120px, 1fr));
    gap: 16px;
  }

  .stat-value {
    font-size: 24px;
  }

  .stat-label {
    font-size: 13px;
  }
}

@media (max-width: 480px) {
  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
    gap: 12px;
  }

  .stat-item {
    padding: 12px;
  }

  .stat-value {
    font-size: 20px;
  }
}
</style>
